﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Herman.Templet.Core;
using Herman.Templet.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;
using static Herman.Templet.Entity.Model.CommonInfo;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Herman.Templet.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize] //为类中所有方法添加认证
    public class ValuesController : ControllerBase
    {
        private readonly SqlSugarClient _db;

        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        /// <param name="db"></param>
        public ValuesController(IHelpDB db)
        {
            this._db = db.OpenDB();
            //_account = new Account();

        }

        /// <summary>
        /// 测试Get
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetData(int abc)
        {
            LogHelp.LogInfo("GetData:" + abc);
            return Ok(new ResultInfo() { Data = "GetData:"+ abc });
        }

        /// <summary>
        /// 测试Post
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostData([FromBody]string data)
        {
            return Ok(new ResultInfo() { Data="PostData:"+ data });
        }

        /// <summary>
        /// 测试Delete
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DeleteData()
        {
            return Ok(new ResultInfo() { Data = "PostData" });
        }

        /// <summary>
        /// 自动生成数据库映射表
        /// </summary>
        [HttpGet]
        public IActionResult AutoCreaterEntity()
        {
            // 直接生成数据库所有实体类，并识别自增长ID 生成类的文件夹地址D:\xxx\DbModels 生成类的命名空间 xxx_Entity
            //_db.DbFirst.IsCreateAttribute().CreateClassFile(@"D:\Item\VS\Gitee\Herman.Templet\Herman.Templet.Entity", "Herman.Templet.Entity");
            //生成数据库单个表的实体类，并识别自增长ID  生成类的文件夹地址D:\xxx\DbModels 生成类的命名空间 xxx_Entity

            _db.DbFirst.IsCreateAttribute().Where("Account").CreateClassFile(@"D:\Item\VS\Gitee\Herman.Templet\Herman.Templet.Entity", "Herman.Templet.Entity");

            return Ok();
        }

        /// <summary>
        /// 测试Post
        /// </summary>
        /// <returns></returns>
        [Authorize]//单个方法添加认证 可以为整个Controller 添加认证 （在类上添加同样标记）  单个不需要认证 添加[AllowAnonymous] 标记
        [HttpPost]
        public IActionResult TestAuthorize([FromBody] string data)
        {
            //获取认证信息
            var userID = Convert.ToInt32(User.FindFirst("UserID").Value);
            var userName = User.FindFirst("UserName").Value;
            var roles = User.FindFirst("Roles").Value;

            return Ok(new ResultInfo() { Data = "PostData:" + data + " UserInfo：" + JsonConvert.SerializeObject(new { UserID = userID, UserName = userName, Roles = roles }) });
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login([FromBody] JwtUserInfo userInfo)
        {
            #region 登录逻辑
            //编写登录业务逻辑
            #endregion

            //根据用户信息生成Token
            var generateJwt = new GenerateJwt();
            string token;
            try
            {
                token = generateJwt.GenerateEncodedToken(userInfo.UserName, userInfo);
            }
            catch (Exception e)
            {
                LogHelp.LogError("CreateJWT ERROR:" + e.Message + "/r/n 请求源数据:" + JsonConvert.SerializeObject(userInfo));
                return BadRequest();
            }

            //返回用户信息及token
            return Ok(new { userInfo.UserID, userInfo.UserName, userInfo.Roles, Token = token });
        }

        #region Account CRUD Demo 详细文档：http://www.codeisbug.com/Doc/8/1121

        /// <summary>
        /// 新增账户
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult InsertAccount([FromBody] Entity.Account account)
        {
            var id = _db.Insertable(account).ExecuteReturnIdentity();
            return Ok(new ResultInfo { Data = id.ToString() });
        }

        /// <summary>
        /// 删除账户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Deleteccount([FromBody] int id)
        {
            var result= _db.Deleteable<Entity.Account>(id).ExecuteCommand();
            return Ok(new ResultInfo() { Data= result.ToString() });
        }

        /// <summary>
        /// 修改账户信息
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateAccount([FromBody] Entity.Account account)
        {
            var result = _db.Updateable(account).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
            return Ok(new ResultInfo() { Data = result.ToString() });
        }

        /// <summary>
        /// 获取账户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAccount()
        {
            var result=_db.Queryable<Entity.Account>().Where(a => a.Age > 20).ToJson();
            //Ado执行sql
            //var result = _db.Ado.GetDataTable(@"select * from dbo.Account where Age>@age", new SugarParameter("@agr", 20));
            return Ok(new ResultInfo(){ Data= result });
        }
        
        #endregion
    }
}
